package com.aaa.service.mht.impl;

import com.aaa.dao.mht.TmhtSubMapper;
import com.aaa.entity.MyPage;
import com.aaa.entity.TmhtSub;
import com.aaa.service.mht.TmhtSubService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * (TmhtSub)表服务实现类
 *
 * @author yuyongli
 * @since 2022-10-22 17:05:01
 */
@Service
public class TmhtSubServiceImpl implements TmhtSubService {
   @Autowired
   private TmhtSubMapper tmhtSubMapper;

   @Override
   public void dealFile(MultipartFile file) {
      int i = tmhtSubMapper.selectCount(null);
     if(i>0){
        return;
     }else {
        InputStream is = null;
        try {
           is = file.getInputStream();
        } catch (IOException e) {
           e.printStackTrace();
        }
        EasyExcel.read(is, TmhtSub.class, new AnalysisEventListener<TmhtSub>() {
           public static final int BATCH_COUNT = 100;
           private List<TmhtSub> cachedDataList = new ArrayList<>();
           @Override
           public void invoke(TmhtSub data, AnalysisContext context) {
              cachedDataList.add(data);
              if (cachedDataList.size() >= BATCH_COUNT) {
                 saveData();
                 // 存储完成清理 list
                 cachedDataList = new ArrayList<>();
              }
           }
           @Override
           public void doAfterAllAnalysed(AnalysisContext context) {
              saveData();
           }
           private void saveData() {
//            log.info("{}条数据，开始存储数据库！", cachedDataList.size());
//            log.info("存储数据库成功！");
              save(cachedDataList);
           }
        }).sheet("MHT量表").doRead();
     }
   }

   @Override
   public void save(List<TmhtSub> list) {
      tmhtSubMapper.insertmthSubjects(list);
   }

    @Override
    public PageInfo getAll(MyPage myPage) {

       PageHelper.startPage(myPage.getPage(),myPage.getLimit());

        return new PageInfo(tmhtSubMapper.selectAll());
    }

   @Override
   public boolean insertMht(TmhtSub tmhtSub) {
      boolean b = tmhtSubMapper.insertMht(tmhtSub);
      return b;
   }
}

